/**
 * @file
 * Ethernet Interface Skeleton
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

/*
 * This file is a skeleton for developing Ethernet network interface
 * drivers for lwIP. Add code to the low_level functions and do a
 * search-and-replace for the word "eth0" to replace it with
 * something that better describes your network interface.
 */

#include "lwip/opt.h"

#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "lwip/ethip6.h"
#include "lwip/etharp.h"
#include "netif/ppp/pppoe.h"

#include "bsp_ethernet.h"

#include <string.h>

/* Define those to better describe your network interface. */
#define IFNAME0 'e'
#define IFNAME1 'n'

#define MTU_LEN (1500) //网络层数据包的最大长度

/* 分配两个数组用于存储收发的数据包 */
static uint8_t mac_transmit_buf[MTU_LEN]; /* 后面low_level_output时会用到，用于存放拼接后的发送报文 */
static uint8_t mac_receive_buf[MTU_LEN];  /* 后面low_level_input时会用到，用于存放完整的接收报文 */

/**
 * Helper struct to hold private data used to operate your ethernet interface.
 * Keeping the ethernet address of the MAC in this struct is not necessary
 * as it is already kept in the struct netif.
 * But this is only an example, anyway...
 */
struct eth0
{
    struct eth_addr *ethaddr;
};

/**
 * 此函数用于初始化网卡硬件，同时设置netif结构体的一些参数，其被
 * eth0_init()调用（没错，我给ethernetif_init换了个名字）
 *
 * @param netif 已经分配好空间的，用于eth0网卡的LwIP网络接口结构体
 */
static void
low_level_init(struct netif *netif)
{
    struct eth0 *eth0 = netif->state; /* 这里挂载了用户传入的自定义网络接口参数结构体，在这可有可无 */
    uint8_t mac[ETHARP_HWADDR_LEN];

    LWIP_DEBUGF(NETIF_DEBUG, ("low_level_init: start low level init.\n"));
    LWIP_ASSERT(("low_level_init: eth0 != NULL.\r\n"), eth0);

    /* 设置MAC地址长度，对于以太网其为6 */
    netif->hwaddr_len = ETHARP_HWADDR_LEN;

    /* 
     * 获取以太网地址，这里作者自己将MAC地址封装在底层，并提供了获取的接口、
     * 获取到的MAC地址存在mac数组中，自己网上用MAC生成器生成一个填入数组也一样
     */
    if (Bsp_Ethernet_GetAddr(mac, ETHARP_HWADDR_LEN) != ETH_OK)
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("low_level_init: mac address get failure.\n"));
    }

    /* 将网卡地址填入网络接口结构体 */
    netif->hwaddr[0] = mac[0];
    netif->hwaddr[1] = mac[1];
    netif->hwaddr[2] = mac[2];
    netif->hwaddr[3] = mac[3];
    netif->hwaddr[4] = mac[4];
    netif->hwaddr[5] = mac[5];

    /* 网络层数据包的最大长度，一般为1500 */
    netif->mtu = MTU_LEN;

    /* 设备功能配置 */
    /* 可以不深究，想知道更多去读这些宏定义的注释吧 */
    netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;

    /* 调用网卡驱动的初始化函数来初始化网卡驱动 */
    if (Bsp_Ethernet_Init() != ETH_OK)
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("low_level_init: initiate mac hardware failure.\n"));
    }
}

/**
 * 此函数用于做实际的数据包发送工作。数据包将会被封装在pbuf结构中传入这个函数。pbuf可能是一个
 * 链表结构，也就是说一个数据包可能在多个pbuf链接起来的链表里，需要读出来拼好。
 *
 * @param netif eth0这张网卡的网络接口结构体
 * @param p 需要发送的MAC层数据包
 * @return ERR_OK 数据包成功发送返回ERR_OK
 *         数据包发送失败时返回对应的ERR_xxx错误码
 *
 * @note 如果底层网卡的发送缓冲满了导致发送失败，不建议返回ERR_MEM，因为这会
 *       导致LwIP丢弃这个数据包（使用TCP协议的情况除外），可以的话，试着等待
 *       缓冲有空间了再发送这个数据包。（翻译的不好，保留原文）
 *       Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
 *       strange results. You might consider waiting for space in the DMA queue
 *       to become available since the stack doesn't retry to send a packet
 *       dropped because of memory failure (except for the TCP timers).
 */

static err_t
low_level_output(struct netif *netif, struct pbuf *p)
{
    struct pbuf *q;
    uint16_t mac_packet_cnt; /* 数据包长度计数 */

#if ETH_PAD_SIZE
    pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif

    /* 拼接pbuf中的数据到一起 */
    for (q = p, mac_packet_cnt = 0; q != NULL; q = q->next)
    {
        /* Send the data from the pbuf to the interface, one pbuf at a
       time. The size of the data in each pbuf is kept in the ->len
       variable. */

        /* 拼接前确保还有足够空间 */
        if (mac_packet_cnt + q->len > MTU_LEN)
        {
            //空间已经超出最大限制了，报错返回
            LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output: packet len error, len > mtu.\r\n"));
            return ERR_BUF;
        }

        /* 将当前pbuf中数据放入缓冲 */
        memcpy((void *)&(mac_transmit_buf[mac_packet_cnt]), q->payload, q->len);
        mac_packet_cnt += q->len;
    }

    /* 校验数据长度无误，然后发送数据 */
    if (mac_packet_cnt == p->tot_len)
    {
        eth_result ret;        /* 记录发送结果 */
        uint8_t retry_cnt = 0; /* 重试计数 */
        do
        {
            ret = Bsp_Ethernet_Transmit(mac_transmit_buf, mac_packet_cnt);
            if (ret == ETH_OK)
            {
                break;
            }
            retry_cnt++;
        } while (retry_cnt < 10);

        if (ret != ETH_OK)
        {
            /* 由于发送重试过多退出来的 */
            LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output: packet send fail.\r\n"));
            return ERR_IF;
        }
    }
    else
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output: packet len error, tot_len != mac_packet_cnt.\r\n"));
        return ERR_BUF;
    }

    MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p->tot_len);
    if (((u8_t *)p->payload)[0] & 1)
    {
        /* broadcast or multicast packet*/
        MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts);
    }
    else
    {
        /* unicast packet */
        MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
    }

#if ETH_PAD_SIZE
    pbuf_add_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif

    LINK_STATS_INC(link.xmit);

    return ERR_OK;
}

/**
 * 此函数应该从堆中动态分配一个pbuf并将从底层网络接口收到的数据包字节丢入pbuf
 *
 * @param netif 这张网卡的以太网接口netif数据结构
 * @return 填充了数据包的pbuf (包括MAC层的以太网首部)
 *         如果发生内存错误（比如pbuf分配失败）则返回NULL
 */
static struct pbuf *
low_level_input(struct netif *netif)
{
    struct pbuf *p, *q;
    u16_t len;
    eth_result ret;
    uint32_t read_index; /* 记录当前的读下标 */

    /* 从网卡获取数据以及数据长度 */
    ret = Bsp_Ethernet_Receive(mac_receive_buf, MTU_LEN, &len);
    if (ret != ETH_OK)
    {
        /* 没能读取到数据包 */
        if (ret == ETH_ERR)
        {
            LWIP_DEBUGF(NETIF_DEBUG, ("low_level_input: Bsp_Ethernet_Receive err.\r\n"));
        }
        return NULL;
    }

#if ETH_PAD_SIZE
    len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif

    /* We allocate a pbuf chain of pbufs from the pool. */
    p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
    if (p != NULL)
    {

#if ETH_PAD_SIZE
        pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif

        /* We iterate over the pbuf chain until we have read the entire
         * packet into the pbuf. */
        read_index = 0;
        for (q = p; q != NULL; q = q->next)
        {
            /* Read enough bytes to fill this pbuf in the chain. The
             * available data in the pbuf is given by the q->len
             * variable.
             * This does not necessarily have to be a memcpy, you can also preallocate
             * pbufs for a DMA-enabled MAC and after receiving truncate it to the
             * actually received size. In this case, ensure the tot_len member of the
             * pbuf is the sum of the chained pbuf len members.
             */
            /* 将数据包填入pbuf */
            memcpy(q->payload, &(mac_receive_buf[read_index]), q->len);
            read_index += q->len;
            if (read_index >= len)
            {
                break;
            }
        }

        MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);
        if (((u8_t *)p->payload)[0] & 1)
        {
            /* broadcast or multicast packet*/
            MIB2_STATS_NETIF_INC(netif, ifinnucastpkts);
        }
        else
        {
            /* unicast packet*/
            MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
        }
#if ETH_PAD_SIZE
        pbuf_add_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif

        LINK_STATS_INC(link.recv);
    }
    else
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("low_level_input: pbuf alloc failure.\r\n"));
        LINK_STATS_INC(link.memerr);
        LINK_STATS_INC(link.drop);
        MIB2_STATS_NETIF_INC(netif, ifindiscards);
    }

    return p;
}

/**
 * This function should be called when a packet is ready to be read
 * from the interface. It uses the function low_level_input() that
 * should handle the actual reception of bytes from the network
 * interface. Then the type of the received packet is determined and
 * the appropriate input function is called.
 *
 * @param netif the lwip network interface structure for this eth0
 * @return err_t ERR_OK if we get ethernet packet
 */
err_t eth0_input(struct netif *netif)
{
    struct pbuf *p;

    /* move received packet into a new pbuf */
    p = low_level_input(netif);
    /* if no packet could be read, silently ignore this */
    if (p != NULL)
    {
        /* pass all packets to ethernet_input, which decides what packets it supports */
        if (netif->input(p, netif) != ERR_OK)
        {
            LWIP_DEBUGF(NETIF_DEBUG, ("eth0_input: IP input error\n"));
            pbuf_free(p);
            p = NULL;
        }

        return ERR_OK;
    }
    return ERR_BUF;
}

/**
 * Should be called at the beginning of the program to set up the
 * network interface. It calls the function low_level_init() to do the
 * actual setup of the hardware.
 *
 * This function should be passed as a parameter to netif_add().
 *
 * @param netif the lwip network interface structure for this eth0
 * @return ERR_OK if the loopif is initialized
 *         ERR_MEM if private data couldn't be allocated
 *         any other err_t on error
 */
err_t eth0_init(struct netif *netif)
{
    struct eth0 *eth0;

    LWIP_ASSERT("netif != NULL", (netif != NULL));

    eth0 = mem_malloc(sizeof(struct eth0));
    if (eth0 == NULL)
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("eth0_init: out of memory\n"));
        return ERR_MEM;
    }

#if LWIP_NETIF_HOSTNAME
    /* Initialize interface hostname */
    netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */

    /*
   * Initialize the snmp variables and counters inside the struct netif.
   * The last argument should be replaced with your link speed, in units
   * of bits per second.
   */
    MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS);

    netif->state = eth0;
    netif->name[0] = IFNAME0;
    netif->name[1] = IFNAME1;
    /* We directly use etharp_output() here to save a function call.
   * You can instead declare your own function an call etharp_output()
   * from it if you have to do some checks before sending (e.g. if link
   * is available...) */
#if LWIP_IPV4
    netif->output = etharp_output;
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
    netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 */
    netif->linkoutput = low_level_output;

    eth0->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);

    /* initialize the hardware */
    low_level_init(netif);

    return ERR_OK;
}
